package com.tanhua.server.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.Constants;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.db.UserApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private UserFreezeService userFreezeService;
    @Autowired
    private MqMessageService mqMessageService;


    /**
     * 登陆--获取验证码
     * @param phone
     */
    public void sendCodeForLogin(String phone) {
        String key = "LOGIN_CODE_" + phone;
        //若redis存在验证码，则抛出异常
        String code = redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(code))
            throw new TanHuaException(ErrorResult.duplicate());

        //String randomCode = RandomStringUtils.randomNumeric(6);
        String randomCode = "123456";
        if(false)
            smsTemplate.sendSms(phone, randomCode);
        redisTemplate.opsForValue().set(key, randomCode, 5, TimeUnit.MINUTES);
    }

    /**
     * 登陆--验证码校验 登陆
     * @param phone
     * @param code
     * @return
     */
    public Map login(String phone, String code) {
        String key = "LOGIN_CODE_" + phone;
        String redisCode = redisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(redisCode))
            throw new TanHuaException(ErrorResult.loginError());

        if(!StringUtils.equals(redisCode, code))
            throw new TanHuaException(ErrorResult.validateCodeError());

        User user = new User();
        user.setMobile(phone);
        user = userApi.find(user);

        boolean isNew = false;
        if(null == user) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(SecureUtil.md5(phone.substring(5)));
            user.setId(userApi.add(user));
            isNew = true;

            //添加进环信数据库
            boolean create = huanXinTemplate.createUser(Constants.HX_USER_PREFIX + user.getId(), Constants.INIT_PASSWORD);
            if (create) {
                user.setHxUser(Constants.HX_USER_PREFIX + user.getId());
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
                mqMessageService.sendLogMessage(user.getId(),  "0101", "user", user.getId().toString());
            }
        }
        //删除验证码
        redisTemplate.delete(key);
        //判断用户是否被冻结
        userFreezeService.checkUserStates(user.getId(), Constants.USER_FREEZE_LOGIN);

        String token = JwtUtils.createToken(user.getId(), phone);
        String tokenKey = "TOKEN_" + token;
        String userJSON = JSON.toJSONString(user);
        redisTemplate.opsForValue().set(tokenKey, userJSON, 1L, TimeUnit.DAYS);
        mqMessageService.sendLogMessage(user.getId(), "0102", "user", user.getId().toString());

        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        map.put("isNew", isNew);
        return map;
    }


    /**
     * 修改手机号- 1 发送短信验证码
     */
    public void sendCodeForModify() {
        User user = new User();
        user.setId(UserHolder.getUserId());
        user = userApi.find(user);

        //TODO 若手机号码和原本的手机号码一样，则不修改 不用发送短信

        String key = "MODIFY_CODE_" + user.getMobile();
        String redisCode = redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(redisCode)) {
            throw new TanHuaException(ErrorResult.duplicate());
        }

        //String randomCode = RandomStringUtils.randomNumeric(6);
        String randomCode = "123123";
        if (false)
            smsTemplate.sendSms(user.getMobile(), randomCode);
        redisTemplate.opsForValue().set(key, randomCode, 5L, TimeUnit.MINUTES);
    }
}
